const Router = require('koa-router');
const {Class} = require('./db');
const router = new Router();

//分类表增加分类接口
router.post('/addClass', async (ctx, next) => {
    const {className,createTime} = ctx.request.body;
    if(className&&createTime){
        await new Class({
            className,
            createTime
        }).save();
    
        ctx.type = 'json'
        ctx.body = {
            status:1,
            msg: '创建成功'
        }
    }else{
        ctx.type = 'json'
        ctx.body = {
            status:0,
            msg: '创建失败，类名不能为空'
        } 
    }
});
//获取所有分类 
router.post('/getClassList', async (ctx, next) => {
    const classList = await Class.find()
    ctx.type = 'json'
    ctx.body = {
        status:1,
        msg: '获取成功',
        data:classList
    }
});
//修改分类 updateClass
router.post('/updateClass', async (ctx, next) => {
    let {id,className,createTime} = ctx.request.body;
    const cl = await Class.findOne({_id: id})
    if(cl){
        cl.className = className;
        cl.createTime = createTime;
        cl.save();
        ctx.body = {
            status:1,
            msg: '修改成功'
        }
    }else{
        ctx.body = {
            status:0,
            msg: '数据不存在'
        }
    }
});
//删除分类接口  
router.post('/delClass', async (ctx, next) => {
    let {id} = ctx.request.body;
    const cl = await Class.findOne({_id: id})
    if(cl){
        cl.remove();
        ctx.body = {
            status:1,
            msg: '删除成功'
        }
    }else{
        ctx.body = {
            status:0,
            msg: '数据不存在'
        }
    }
});




module.exports = router;